package com.spring.learning.web;

import com.spring.learning.entity.UserEntity;
import com.spring.learning.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by wanqi on 17-6-28.
 */
@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/getUsers")
    public List<UserEntity> getUsers(){
        List<UserEntity> users = userMapper.getAll();
        return users;
    }

    @RequestMapping("/getUser")
    public UserEntity getUser(Long id) {
        String key = "user_" + id;
        ValueOperations<String, UserEntity> operations = redisTemplate.opsForValue();

        // 缓存存在
        boolean hasKey = redisTemplate.hasKey(key);
        log.info("UserController.getUser()  hasKey:"+hasKey);

        if (hasKey) {
            UserEntity userEntity = operations.get(key);

            log.info("UserController.getUser() : 从缓存中获取了 >> " + userEntity.toString());
            return userEntity;
        }

        UserEntity user=userMapper.getOne(id);
        operations.set(key, user, 10, TimeUnit.SECONDS);
        log.info("UserController.getUser():  插入缓存 >> " + user.toString());

        return user;
    }

    @RequestMapping("/add")
    public void save(UserEntity user) {
        userMapper.insert(user);
    }

    @RequestMapping(value="update")
    public void update(UserEntity user) {
        userMapper.update(user);
    }

    @RequestMapping(value="/delete/{id}")
    public void delete(@PathVariable("id") Long id) {
        userMapper.delete(id);
    }

}
